﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;

namespace SC
{
    public class BroadCastReceive
    {
        public void Start()
        {
            System.Threading.Thread thread = new System.Threading.Thread(RecvThread);
            thread.IsBackground = true;
            thread.Start();
        }

        public delegate void GetServiceIP(Common.ServerProfile serverProfile);

        public GetServiceIP getServiceIP;

        Common.ServerProfile profile;


        private  void RecvThread()
        {
            try {
                UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, Common.LocalIP.broadcastPort));
                while (true)
                {
                    IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
                    byte[] buf = client.Receive(ref endpoint);
                    profile = Newtonsoft.Json.JsonConvert.DeserializeObject<Common.ServerProfile>(System.Text.Encoding.Default.GetString(buf));
                    //string msg = Encoding.Default.GetString(buf);

                    getServiceIP?.Invoke(profile);
                }
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                Common.Log.Error(ex.Message);
            }
        }
    }
}
